package org.logistics;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.logistics.bean.ActivityMangager;
import org.logistics.bean.MapInforBean;
import org.logistics.R;



import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MKMapViewListener;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.mapapi.map.Symbol;
import com.baidu.mapapi.map.TextItem;
import com.baidu.mapapi.map.TextOverlay;
import com.baidu.mapapi.utils.CoordinateConvert;
import com.baidu.platform.comapi.basestruct.GeoPoint;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
/**
 * 
 * @author yimou
 * 主界面
 */ 
public class MainMapActivity extends Activity {
	
	private BMapManager bMapManager = null ;
	/**
	 * 坐标对象集合
	 */
	List<GeoPoint> geoPointList = new ArrayList<GeoPoint>();
	List<OverlayItem > overLayList = new ArrayList<OverlayItem>();
	/**
	 * 文字显示集合
	 */
	List<TextItem> textItemList = new ArrayList<TextItem>();
	/**
	 * 坐标接口对象集合
	 */
	List<MapInforBean> mapInforList = new ArrayList<MapInforBean>();
	/**
	 * 包名
	 */
	final static String TAG = "org.MainMapActivity.logistics";
	/**
	 *  MapView 是地图主控件
	 */
	private MapView mMapView = null;
	/**
	 *  用MapController完成地图控制 
	 */
	private MapController mMapController = null;
	/**
	 *  MKMapViewListener 用于处理地图事件回调
	 */
	MKMapViewListener mMapListener = null;
	
	/**
	 * 账号
	 */
	private String userAccount;
	/**
	 * 定位中心点号码
	 */
	private int centerNum;
	
	/**
	 * 定时刷新的线程
	 */
	private Handler handler = new Handler();
	private Runnable runnable = new Runnable() {
        public void run() {
        	handler.removeCallbacks(runnable);
            this.update();
        }
        void update() {
        	Toast.makeText(getApplicationContext(), "刷新数据",
       		     Toast.LENGTH_SHORT).show();
        	
        	//刷新次数加一
        	refreshTimes++;
        	Log.i(TAG, "刷新"+refreshTimes+"次");
        	
        	//重置全局数据
        	 geoPointList = new ArrayList<GeoPoint>();
        	 overLayList = new ArrayList<OverlayItem>();
        	 textItemList = new ArrayList<TextItem>();
        	 mapInforList = new ArrayList<MapInforBean>();
        	 p = null;
        	 
        	 //请求服务器
        	 try {
 				mapInforList = getLocalPlace();
 			} catch (IllegalStateException e) {
 				// TODO Auto-generated catch block
 				e.printStackTrace();
 			} catch (JSONException e) {
 				// TODO Auto-generated catch block
 				e.printStackTrace();
 			} catch (IOException e) {
 				// TODO Auto-generated catch block
 				e.printStackTrace();
 			}
        	 
        	 //30秒刷新一次
        	 refresh();
        }
    }; 
    
    /**
     * 刷新次数
     */
    private int refreshTimes = 0;
    /**
     * 定位中心点
     */
    GeoPoint p  = null;
    
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		ActivityMangager.addActivity(this);
		super.onCreate(savedInstanceState);
		
//		if(refreshTimes == 0){
//		KeyManager app = (KeyManager)this.getApplication();
//        if (app.mBMapManager1 == null) {
//            app.mBMapManager1 = new BMapManager(this);
//            /**
//             * 如果BMapManager没有初始化则初始化BMapManager
//             */
//            app.mBMapManager1.init(KeyManager.strKey2,new KeyManager.MyGeneralListener());
//        }
//	}
		
		setContentView(R.layout.activity_main_map);
		
		//得到用户账号
		Intent intent = new Intent();
		intent = getIntent();
		userAccount = intent.getStringExtra("userAccount");
		centerNum = intent.getIntExtra("centerNum" , 0);
		
		//请求服务器
		 try {
				mapInforList = getLocalPlace();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
	        
		   mMapView = (MapView)findViewById(R.id.bmapView);
		   mMapView.setBuiltInZoomControls(true);
			/**
	        * 获取地图控制器
	        */
	       mMapController = mMapView.getController();
	       /**
	        *  设置地图是否响应点击事件  .
	        */
	       mMapController.enableClick(true);
	       /**
	        * 设置地图缩放级别
	        */
	       mMapController.setZoom(16);
	       
	       //30秒刷新一次
	       refresh();
       
	}
	


	/**
	 * 回调处理函数
	 */
	@Override  
	protected void onDestroy(){  
	        mMapView.destroy();  
	        if(bMapManager!=null){  
	        	bMapManager.destroy();  
	        	bMapManager=null;  
	        }  
	        handler.removeCallbacks(runnable); //停止刷新
	        super.onDestroy();  
	}  
	@Override  
	protected void onPause(){  
		mMapView.setVisibility(View.INVISIBLE);
		
	        mMapView.onPause();  
	        if(bMapManager!=null){  
	        	bMapManager.stop();  
	        } 
	        handler.removeCallbacks(runnable); //停止刷新
	        super.onPause();  
	}  
	@Override  
	protected void onResume(){  
		mMapView.setVisibility(View.VISIBLE);
	        mMapView.onResume();  
	        if(bMapManager!=null){  
	        	bMapManager.start();  
	        }  
	        handler.post(runnable);
	        super.onResume(); 
	} 
	
	/**
	 * 循环代码
	 */
	public void refresh(){
		 
			LocationData locData = new LocationData();  
			Log.i(TAG, "centerNum = "+ centerNum);
			if(centerNum < 0){
			locData.latitude = (double)(mapInforList.get(2).getH());  
		    locData.longitude = (double)(mapInforList.get(2).getI());  
	       //locData.direction = 2.0f;
			}else if(centerNum > 0){
				locData.latitude = (double)(mapInforList.get(centerNum).getH());  
			    locData.longitude = (double)(mapInforList.get(centerNum).getI());  
		       //locData.direction = 2.0f;
			}
	       GeoPoint ep = new GeoPoint((int)(locData.latitude*1e6),  
	    	       (int)(locData.longitude* 1e6));
	        p = CoordinateConvert.fromWgs84ToBaidu(ep);
     	   
	        mMapController.setCenter(p);
	        
	        Drawable mark= getResources().getDrawable(R.drawable.nav_turn_via_1);
	       
	       changeTextObject();
	       
	       changeGeoPointObject(mark);
	       
	       OverLayClass itemOverlay = new OverLayClass(mark, mMapView) ;
	       TextOverlay textOverlay = new TextOverlay(mMapView);
	       
	       //清理前一次的图层
	       mMapView.getOverlays().clear();
	       
	       int len = textItemList.size();
	       for(int i = 0 ; i < len ; i++)
	       {
	    	   textOverlay.addText(textItemList.get(i));
	       }
	       itemOverlay.addItem(overLayList);
	       
	       mMapView.getOverlays().add(itemOverlay); 
	       mMapView.getOverlays().add(textOverlay);
	       
	       mMapView.refresh(); 
	       handler.postDelayed(runnable, 1000 * 30);
		
	}
	
	
	/**
	 * 转化文字坐标图层
	 */
	private void changeTextObject() {
		
		//颜色定义
		Symbol textSymbol = new Symbol();  
	   	Symbol.Color textColor = textSymbol.new Color();  
	   	textColor.alpha = 255;  
	   	textColor.red = 0;  
	   	textColor.blue = 255;  
	   	textColor.green = 0;  
	   	Symbol textSymbol1 = new Symbol();    
	   	Symbol.Color textColor1 = textSymbol1.new Color();    
	   	textColor1.alpha = 150;    
	   	textColor1.red = 80;    
	   	textColor1.blue = 80;    
	   	textColor1.green = 80;
	   	
	   	int len = mapInforList.size(); 
	   	for(int i = 0 ; i < len ; i++)
	   	{
	   		TextItem textItem = new TextItem();  
	   	   	textItem.fontColor = textColor;  
	   	   	textItem.bgColor = textColor1;  
	   	   	textItem.fontSize = 20;  
	   	   	String carNum = mapInforList.get(i).getCarNum().toString();
	   	   	double speed = mapInforList.get(i).getSpeed();
	   	   	textItem.text = carNum +"---"+ speed+"km/h";  
	   	   	textItem.pt =CoordinateConvert.fromWgs84ToBaidu(new GeoPoint((int) (mapInforList.get(i).getH() * 1E6)
	   	   			, (int) (mapInforList.get(i).getI() * 1E6))); 
	   	   	textItemList.add(textItem);
	   	}
	   	
	   	
	}
	

	
	/**
	 * 把接口数据集合转换成GeoPoint对象集合
	 */
	public void changeGeoPointObject (Drawable mark)
	{
		 int len = mapInforList.size();
	       for(int i = 0 ; i < len ; i++ )
	       {
	    	   double mLat = (double) mapInforList.get(i).getH();
	    	   double mLon = (double) mapInforList.get(i).getI();
	    	   Log.i(TAG, "h="+mLat+" i="+mLon);
	    	   GeoPoint gp = new GeoPoint((int) (mLat * 1E6), (int) (mLon * 1E6));
	    	   GeoPoint p = CoordinateConvert.fromWgs84ToBaidu(gp);  
	    	   geoPointList.add(p);
	       }
	       for(int j = 0 ; j < len ; j++ )
	       {
	    	   OverlayItem item = new OverlayItem(geoPointList.get(j), "item"+j, "item"+j);
	    	   item.setMarker(mark);
	    	   overLayList.add(item);
	       }
	}
	
	
	/**
	 * 
	 *请求服务器得到坐标信息对象
	 * @throws JSONException 
	 * @throws IOException 
	 * @throws IllegalStateException
	 */
	public List<MapInforBean> getLocalPlace() throws JSONException, IllegalStateException, IOException {
		BufferedReader in = null;
		/**
		 * 发送请求
		 */
		try {
			Log.i(TAG, "发出请求");
			String request = "http://sj.jy100.com/GetRealtime2.ashx?userName="+userAccount+"&address=true";
			HttpClient hc = new DefaultHttpClient();
			HttpPost hp = new HttpPost(request);
			HttpResponse response = hc.execute(hp);  
	        in = new BufferedReader(  
	                new InputStreamReader(  
	                        response.getEntity().getContent()));  
	        StringBuffer string = new StringBuffer("");  
	        String lineStr = "";  
	        while ((lineStr = in.readLine()) != null) {  
	            string.append(lineStr + "\n");  
	        }  
	        in.close();  
	        String resultStr = string.toString();  
	        Log.i(TAG, resultStr);
	        
	        /**
	         * 解析字符串
	         */
	        JSONObject jo = new JSONObject(resultStr);
	        
	        /**
	         * 得到数据条数
	         * TotalCount
	         */
	        int totalCount = jo.getInt("TotalCount");
	        Log.i(TAG, "共有"+totalCount+"条数据");
	        
	        /**
	         * 把解析数据转保存在对象
	         */
	        JSONArray jsonList = jo.getJSONArray("RootResults");
	        
	        for(int i = 0 ; i < totalCount ; i++  )
	        {
	        	JSONObject temp = new JSONObject(jsonList.getString(i));
	        	MapInforBean mifb = new MapInforBean();
	        	mifb.setCarNum(temp.getString("A"));
	        	mifb.setiMei(temp.getString("D"));
	        	mifb.setOnLine(temp.getBoolean("F"));
	        	mifb.setLocationTime(temp.getString("G"));
	        	mifb.setH(temp.getDouble("H"));
	        	mifb.setI(temp.getDouble("I"));
	        	mifb.setAngle(temp.getInt("K"));
	        	mifb.setSpeed(temp.getDouble("J"));
	        	mifb.setMileage(temp.getDouble("L"));
	        	mifb.setStatue(temp.getString("M"));
	        	mifb.setAddress(temp.getString("O"));
	        	mapInforList.add(mifb);
	        }
			
		} catch (JSONException e) {
			Log.i(TAG, e.getMessage());
		}finally {  
            if (in != null) {  
                try {  
                    in.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }
		
		return mapInforList;  
		
		
	}
	
	
	
	
	/**
	 * 系统自建
	 */
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main_map, menu);
		return true;
	}

}
